<?php

/**
 * Class to read config file. By default this is [./config.inc.php].
 * This file must contain array variable $config.
 */
class GG_API_Config {

	private static $instance;

	/**
	 * @return GG_API_Config Singleton. Default config based on config file
	 * [./config.inc.php].
	 */
    public static function getDefault() {
        return isset(self::$instance) ?
			self::$instance :
			self::$instance = new self();
    }

	/**
	 * @var array Array like $config in file [lib/config.inc.php].
	 */
	private $configArray = null;

	/**
	 * @var bool true if it was at least one try to read config from file.
	 */
	private $readOnce = false;

	public function __construct() {
	}
	
	public function readFromFile($configFilename = null) {
		$this->readOnce = true;
		if ($configFilename === null) {
			$configFilename = dirname(__FILE__) . "/config.inc.php";
		}
		if (file_exists($configFilename)) {
			$configVarNameWasInUse = false;
			$configBackup = null;
			if (isset($config)) {
				$configVarNameWasInUse = true;
				$configBackup = $config;
			}
			include $configFilename;
			if (isset($config)) {
				$this->setConfigArray($config);
			}
			if ($configVarNameWasInUse) {
				$config = $configBackup;
			}
		}
		return $this->getConfigArray();
	}

	public function getConfigArray() {
		$config = $this->configArray;
		if ($config === null) {
			if ($this->readOnce === false) {
				$config = $this->readFromFile();
			} else {
				$config = array();
			}
		}
		return $config;
	}

	/**
	 * @param array $configArray
	 */
	public function setConfigArray($configArray) {
		if (is_array($configArray)) {
			$this->configArray = $configArray;
		}
	}

	/**
	 * @param string $key One of config keys like: oauthConsumerKey,
	 * oauthConsumerSecret.
	 * 
	 * @return mixed Returns config array if key is null, else returns value
	 * by key from config array.
	 */
	public function get($key = null, $default = null) {
		$config = $this->getConfigArray();
		if ($key !== null) {
			if (array_key_exists($key, $config)) {
				return $config[$key];
			} else {
				return $default;
			}
		} else {
			return $config;
		}
	}

	public function getOauthConsumerKey() {
		return $this->get('oauthConsumerKey');
	}

	public function getOauthConsumerSecret() {
		return $this->get('oauthConsumerSecret');
	}

	public function getOauthToken() {
		return $this->get('oauthToken');
	}
	
	public function getOauthTokenSecret() {
		return $this->get('oauthTokenSecret');
	}

	public function getFormat() {
		return $this->get('format');
	}

	public function getJsonpCallback() {
		return $this->get('jsonpCallback');
	}

	public function getUseRequestParams() {
		return $this->get('useRequestParams');
	}

	public function getStore() {
		return $this->get('store');
	}
}

?>
